package com.cdm.forum.exception;


import com.cdm.forum.common.Result;
import com.cdm.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局捕获处理异常
 */

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)//捕获ApplicationException异常
    public Result applicationException(final ApplicationException e) {
        //打印堆栈信息
        e.printStackTrace();
        //打印异常信息
        log.error(e.getMessage(), e);
        //看看ApplicationException里面的属性里面有没有值，有的话直接返回
        if(e.errorResult != null) {
            return e.getErrorResult();
        }
        //非空校验
        if(e.getMessage() == null || "".equals(e.getMessage())) {
            return Result.failed(ResultCode.ERROR_SERVICES);
        }
        //返回具体的异常信息
        return Result.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result exception(final Exception e) {
        //打印堆栈信息
        e.printStackTrace();
        //打印异常信息
        log.error(e.getMessage(), e);
        //非空校验
        if(e.getMessage() == null || "".equals(e.getMessage())) {
            return Result.failed(ResultCode.ERROR_SERVICES);
        }
        //返回异常信息
        return Result.failed(e.getMessage());
    }
}
